package com.cityguardian.threads;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.cityguardian.cityguardianapp.AlertDetailActivity;
import com.cityguardian.cityguardianapp.CorrectiveActivity;
import com.cityguardian.cityguardianapp.MapActivity;
import com.cityguardian.cityguardianapp.SearchActivity;
import com.cityguardian.model.Alerta;
import com.cityguardian.model.Usuario;
import com.cityguardian.utils.Utils;
import com.cityguardian.ws.ConnectionThread;
import com.google.gson.Gson;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.widget.Toast;

public class AsyncTaskGetUserAlert extends AsyncTask<String, Double, String> {
	
	public final static String EXTRA_MESSAGE = "com.cityguardian.cityguardian.mainMessage";	
	private ProgressDialog dialog;
	private ActionBarActivity activity;
	private String idUsuario;
	private String idAlerta;
	private Usuario usuario;
	private Usuario tercero;
	private Alerta alerta;
	private String tipo;
	private String idPostServicio;

	public AsyncTaskGetUserAlert(ActionBarActivity activ, String idUsuario, 
			String idAlerta, String tipo, String idPostServicio){
		this.activity=activ;
		this.dialog = new ProgressDialog(activity);
		this.idUsuario = idUsuario;
		this.idAlerta = idAlerta;
		this.tipo = tipo;
		this.idPostServicio = idPostServicio;
	}
	
    @Override
    protected void onPreExecute() {
        this.dialog.setMessage("Conectando");
        this.dialog.show();
    	Log.e("GETUSER", idUsuario);
    }
    
	@Override
	protected String doInBackground(String... params) {
		
		String response=null;
		if (tipo.equals("empresa")||tipo.equals("emergencia")){
			Context context = this.activity.getApplicationContext();
			String user = Utils.getLocalUser(context);
			response=getInfoAdd(user);				
		}else if (tipo.equals("postservicio")){
			getUsuAlert();
			response=getPostServicio();
		}else{
			response=getUsuAlert();
		}
		
		return response;
	}
	
	@Override
	protected void onPostExecute(String result) {
		
		if (this.dialog.isShowing()) {
			this.dialog.dismiss();
		}
		if ( result== null){
			Toast.makeText(activity, 
					"Error al cargar usuario o alerta", Toast.LENGTH_LONG).show();
			return;
		}else{
			
			if (tipo.equals("emergencia")){
				
				Intent intent = new Intent(this.activity, MapActivity.class);
				intent.putExtra("Alerta", alerta);
				intent.putExtra("Usuario", usuario);
				intent.putExtra("Tercero",tercero);
				intent.putExtra("tipo", tipo);
				
				this.activity.startActivity(intent);
				this.activity.finish();
				
				return;
			}else if (tipo.equals("postservicio")){
				Intent intent = new Intent(this.activity, CorrectiveActivity.class);
				intent.putExtra("Usuario", usuario);
				intent.putExtra("idPostServicio", idPostServicio);
				intent.putExtra("acciones", result);
				intent.putExtra("Alerta",alerta);
				
				this.activity.startActivity(intent);
				this.activity.finish();
				
				return;
			}
			
			Intent intent;
			if (tipo.equals("incidente")){
				intent = new Intent(this.activity, SearchActivity.class);
			}else{
				intent = new Intent(this.activity, AlertDetailActivity.class);
			}
			intent.putExtra("Alerta", alerta);
			intent.putExtra("Usuario", usuario);
			intent.putExtra("Tercero",tercero);
			intent.putExtra("tipo", tipo);
			
			this.activity.startActivity(intent);
			this.activity.finish();
		}
	}
	
	private String getUsuAlert() {
		
		List<NameValuePair> param = new ArrayList<NameValuePair>();								
		param.add(new BasicNameValuePair("idUsuario", idUsuario));
		String route="/ws/usuario/get_user_by_id/";
		
		ConnectionThread connection = new ConnectionThread(param, route);
		String responseBody = connection.getResponse();
		
		if (responseBody==null){
			Log.e("log_tag", "Error in webservice");
			return null;
		}

	    Gson gson = new Gson();
	    Log.e("log_tag", responseBody);
		usuario = gson.fromJson(responseBody,Usuario.class);				    
		
		param = new ArrayList<NameValuePair>();								
		param.add(new BasicNameValuePair("idAlerta", idAlerta));
		route="/ws/alerta/get_alert_by_id/";
		
		connection = new ConnectionThread(param, route);
		responseBody = connection.getResponse();
		
		if (responseBody==null){
			Log.e("log_tag", "Error in webservice");
			return null;
		}
		
		gson = new Gson();
	    Log.e("log_tag", responseBody);
		alerta = gson.fromJson(responseBody,Alerta.class);
		
		return "1";
	}
	
	private String getInfoAdd(String localUser) {
		
		List<NameValuePair> param = new ArrayList<NameValuePair>();								
		param.add(new BasicNameValuePair("idUsuario", localUser));
		String route="/ws/usuario/get_user_by_id/";
		
		ConnectionThread connection = new ConnectionThread(param, route);
		String responseBody = connection.getResponse();
		
		if (responseBody==null){
			Log.e("log_tag", "Error in webservice");
			return null;
		}

	    Gson gson = new Gson();
	    Log.e("log_tag", responseBody);
		usuario = gson.fromJson(responseBody,Usuario.class);				    
		
		param = new ArrayList<NameValuePair>();								
		param.add(new BasicNameValuePair("idUsuario", idUsuario));
		route="/ws/usuario/get_user_by_id/";
		
		connection = new ConnectionThread(param, route);
		responseBody = connection.getResponse();
		
		if (responseBody==null){
			Log.e("log_tag", "Error in webservice");
			return null;
		}

	    gson = new Gson();
	    Log.e("log_tag", responseBody);
		this.tercero = gson.fromJson(responseBody,Usuario.class);	
		
		param = new ArrayList<NameValuePair>();
		if (!tipo.equals("emergencia"))
			param.add(new BasicNameValuePair("idUsuario", idUsuario));
		param.add(new BasicNameValuePair("idAlerta", idAlerta));
		
		if (tipo.equals("emergencia")){
			route="/ws/alerta/get_alert_by_id/";			
		}else{
			route="/ws/alerta/get_alert_info_add/";
		}
		
		connection = new ConnectionThread(param, route);
		responseBody = connection.getResponse();
		
		if (responseBody==null){
			Log.e("log_tag", "Error in webservice");
			return null;
		}
		
		gson = new Gson();
	    Log.e("log_tag", responseBody);
		alerta = gson.fromJson(responseBody,Alerta.class);
		
		return "1";
	}
	
	private String getPostServicio() {
		
		List<NameValuePair> param = new ArrayList<NameValuePair>();	
		param = new ArrayList<NameValuePair>();								
		param.add(new BasicNameValuePair("idPostServicio", idPostServicio));
		String route="/ws/postservicio/get_acciones/";
		
		ConnectionThread connection = new ConnectionThread(param, route);
		String responseBody = connection.getResponse();
		
		if (responseBody==null){
			Log.e("log_tag", "Error in webservice");
			return null;
		}
		
		String texto=null;
		JSONArray listaAcciones = null;
		try {
			texto="";
			listaAcciones = new JSONArray(responseBody);
			for (int i=0;i<listaAcciones.length();i++){				
				JSONObject accion = listaAcciones.getJSONObject(i);
				int j=i;
				texto+=""+(++j)+") "+accion.optString("descripcion")+"\n";				
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return texto;
	}

}
